package lesson05.c3p0;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 所有的池化技术都会实现 DataSource 这个接口
 * 数据库连接池C3P0测试
 */
public class TestC3P0 {
    public static void main(String[] args) {
        // 获取DataSource，使用指定名称配置(不传递指定名称配置则使用配置文件中的默认配置)
        DataSource ds = new ComboPooledDataSource("otherC3P0");;

        // 查看连接池中的数据库连接对象
        viewConnection(ds);

        Connection conn = null;
        try {
            // 获取数据库连接
            conn = ds.getConnection();
            // 编写查询语句
            String sql = "SELECT * FROM test_table";
            // 获取PreparedStatement对象并预编译sql（PreparedStatement对象防止sql注入）
            PreparedStatement statement = conn.prepareStatement(sql);
            // 执行查询语句获得查询结果
            ResultSet resultSet = statement.executeQuery();
            // 处理查询结果
            while (resultSet.next()) {
                String test1 = resultSet.getString("test1");
                String makeLendingTime = resultSet.getString("MAKE_LENDING_TIME");
                String isRepayLending = resultSet.getString("IS_REPAY_LENDING");

                System.out.println("test1: " + test1 + ", makeLendingTime: " + makeLendingTime + ", isRepayLending: " + isRepayLending);
            }
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                // 归还连接
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    /**
     * 查看连接池的连接数
     * @param ds 连接池对象
     */
    private static void viewConnection(DataSource ds) {
        try {
            //2.获取连接
            for (int i = 1; i <= 5; i++) {
                Connection conn = ds.getConnection();
                System.out.println(i + ":" + conn);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
